package com.yc.star.booksystem.interceptor;


import com.yc.star.booksystem.constants.Constants;
import com.yc.star.booksystem.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 目标方法执行前执行
        // true：放行 false: 拦截
        HttpSession session = request.getSession();
        UserInfo userSession = (UserInfo) session.getAttribute(Constants.USER_SESSION_KEY);
        if (userSession == null || userSession.getId() < 1) {
            // 返回HTTP状态码
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
